package com.changcheng.project.yuminsi.service.impl;

import com.alibaba.fastjson.JSON;

import com.changcheng.project.yuminsi.mapper.CommonMapper;
import com.changcheng.project.yuminsi.domain.OperInfoDomain;
import com.changcheng.project.yuminsi.domain.UserDomain;
import com.changcheng.project.yuminsi.error.BusinessException;
import com.changcheng.project.yuminsi.error.GlobalErrorCode;
import com.changcheng.project.yuminsi.service.OperpermService;
import com.changcheng.project.yuminsi.utils.GenerateSignUtil;
import com.changcheng.project.yuminsi.vo.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @author yuminsi
 * @description
 * @date 2020/9/11 11:13
 * @since
 */
@SuppressWarnings("all")
@Service
public class OperpermServiceImpl implements OperpermService {

    private static final Logger logger = LoggerFactory.getLogger(OperpermServiceImpl.class);

    @Autowired
    private CommonMapper commonMapper;

    @Autowired
    private HttpServletRequest request;

    private static String appkey = "9065275281";
    private static String secretkey = "2b673290caa2d9a82f1f7e845c80e4fe";

    /**
     * 用户登陆接口
     *
     * @param userLoginRequest
     * @return
     */
    @Override
    public BaseOutput loginForDealer(UserLoginRequest userLoginRequest) throws Exception {
        //签名
        String sign = request.getHeader("bt-auth-sign");
        logger.info("sign签名： {}",sign);
        //header
        String appkey = request.getHeader("bt-auth-appkey");
        String nonce = request.getHeader("bt-auth-nonce");
        String timestamp = request.getHeader("bt-auth-timestamp");

        //url
        String uri = request.getRequestURI();

        //参数
        //对象转json
        String userLogin = JSON.toJSONString(userLoginRequest);
        Map<String, Object> postBody = new HashMap<>();
        postBody.put("json", userLogin);
        String genSign = GenerateSignUtil.generateSignOfPost(uri, appkey, nonce, timestamp, postBody, secretkey);
        logger.info("POST生成的签名:  {}", genSign);

        //验证签名
       if (!genSign.equalsIgnoreCase(sign)) {
          throw new BusinessException(GlobalErrorCode.SIGN_FAIL);
        }


        //系统标识，值固定为11
        String systemFlag = request.getHeader("systemFlag");
        String accountName = userLoginRequest.getAccountName();
        String password = userLoginRequest.getPassword();

        //判断账户和密码输入是否为null
        if (StringUtils.isEmpty(accountName)) {
            throw new BusinessException(GlobalErrorCode.ACCOUNT_NAME_NULL);
        }
        if (StringUtils.isEmpty(password)) {
            throw new BusinessException(GlobalErrorCode.ACCOUNT_PASSWORD_NULL);
        }

        //判断操作员是否存在
        OperInfoDomain operInfoDomain = commonMapper.queryOperInfoByAccountName(accountName);
        if (operInfoDomain == null) {
            throw new BusinessException(GlobalErrorCode.OPER_NOT_EXIST);
        }
        if (!password.equals(operInfoDomain.getPassword())) {
            throw new BusinessException(GlobalErrorCode.PASSWORD_ERROR);
        }

        String accessToken = UUID.randomUUID().toString().replace("-", "").substring(0, 32);
        operInfoDomain.setAccessToken(accessToken);
        commonMapper.updateOperInfo(operInfoDomain);

        String phone = operInfoDomain.getPhone();
        UserDomain userDomain = commonMapper.queryUserInfoByPhone(phone);
        UserLoginResponse loginResponse = getLoginResponse(operInfoDomain, userDomain);
        return BaseOutput.responseData(GlobalErrorCode.SUCCESS, loginResponse);
    }

    public UserLoginResponse getLoginResponse(OperInfoDomain operInfoDomain, UserDomain userDomain) {
        UserLoginResponse userLoginResponse = new UserLoginResponse();
        userLoginResponse.setAccountId(Long.valueOf(operInfoDomain.getAccountId()));
        userLoginResponse.setAccountName(operInfoDomain.getAccountName());
        userLoginResponse.setAccessToken(operInfoDomain.getAccessToken());
//        SysSourceEnum sysSourceEnum = SysSourceEnum.acctType(acctInfoDomain.getSysSource().toString());
        userLoginResponse.setSysSource(Integer.valueOf(operInfoDomain.getSysSource()));
//        EnterpriseIdEnum enterpriseId = EnterpriseIdEnum.getEnterpriseId(acctInfoDomain.getEnterpriseId());
        userLoginResponse.setEnterpriseId(operInfoDomain.getEnterpriseId());
        userLoginResponse.setDealerCode(operInfoDomain.getDealerCode());
        userLoginResponse.setDealerName(operInfoDomain.getDealerName());
        userLoginResponse.setName(operInfoDomain.getName());
//         GenderEnum genderType = GenderEnum.getGenderType(userDomain.getGender().toString());
        userLoginResponse.setGender(Integer.valueOf(operInfoDomain.getGender()));
        userLoginResponse.setEmail(operInfoDomain.getEmail());
        userLoginResponse.setPhone(operInfoDomain.getPhone());
        userLoginResponse.setDeptId(Integer.valueOf(operInfoDomain.getDeptId()));
        userLoginResponse.setDeptName(operInfoDomain.getDeptName());

        AuthRoles authRoles = new AuthRoles();
        authRoles.setRoleCode(operInfoDomain.getRoleCode());
        authRoles.setId(1L);
        authRoles.setRoleName("1");
        authRoles.setRoleDesc("1");
        //将对象转成集合
        userLoginResponse.setAuthRoles(Collections.singletonList(authRoles));
        return userLoginResponse;
    }

    /**
     * 账号密码修改接口
     *
     * @param passwordChangeRequest
     * @return
     */
    @Override
    public BaseOutput changePassword(PasswordChangeRequest passwordChangeRequest) throws Exception {
        //签名
        String sign = request.getHeader("bt-auth-sign");
        //header
        String appkey = request.getHeader("bt-auth-appkey");
        String nonce = request.getHeader("bt-auth-nonce");
        String timestamp = request.getHeader("bt-auth-timestamp");

        //url
        String uri = request.getRequestURI();

        //参数
        //对象转json
        String passwordChange = JSON.toJSONString(passwordChangeRequest);
        Map<String, Object> postBody = new HashMap<>();
        postBody.put("json", passwordChange);
        String genSign = GenerateSignUtil.generateSignOfPost(uri, appkey, nonce, timestamp, postBody, secretkey);
        logger.info("POST生成的签名:  {}", genSign);

        //验证签名
       if (!genSign.equalsIgnoreCase(sign)) {
          throw new BusinessException(GlobalErrorCode.SIGN_FAIL);
        }


        //修改账号Id
        Long id = passwordChangeRequest.getId();
        //老密码
        String oldPassword = passwordChangeRequest.getOldPassword();
        //新密码
        String password = passwordChangeRequest.getPassword();
        //确认密码
        String checkPassword = passwordChangeRequest.getCheckPassword();
        //当前登陆账号 Id
        String accountId = request.getHeader("accountId");

        OperInfoDomain operInfoDomain = commonMapper.queryOperInfoByAccountId(Long.valueOf(accountId));
        if (operInfoDomain == null) {
            throw new BusinessException(GlobalErrorCode.OPER_NOT_EXIST);
        }

        //修改密码失败，原密码错误
        if (!oldPassword.equalsIgnoreCase(operInfoDomain.getPassword())) {
            throw new BusinessException(GlobalErrorCode.CHANGE_PASSWORD_FAIL_4);
        }

        //修改密码失败，输入的老密码与新密码相同
        if (password.equalsIgnoreCase(operInfoDomain.getPassword())) {
            throw new BusinessException(GlobalErrorCode.CHANGE_PASSWORD_FAIL_2);
        }

        //修改密码失败，新密码与确认密码输入不一致
        if (!checkPassword.equalsIgnoreCase(password)) {
            throw new BusinessException(GlobalErrorCode.CHANGE_PASSWORD_FAIL_3);
        }

        operInfoDomain.setPassword(password);
        try {
            if (accountId.equals(id)) {
                operInfoDomain.setAccountId(accountId);
                commonMapper.modifyPasswordByAccountId(operInfoDomain);
            } else {
                operInfoDomain.setAccountId(id.toString());
                commonMapper.modifyPasswordByAccountId(operInfoDomain);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(GlobalErrorCode.FAIL);
        }
        return BaseOutput.responseData(GlobalErrorCode.SUCCESS,null);
    }
}